package com.las.bot.cmd.lol;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.las.annotation.BotCmd;
import com.las.bot.dao.LolAreaDao;
import com.las.bot.dao.LolSettingDao;
import com.las.bot.dao.LolTierDao;
import com.las.cmd.BaseCommand;
import com.las.utils.mirai.CmdUtil;
import com.model.LolArea;
import com.model.LolSetting;
import com.model.LolTier;
import com.utils.DateUtils;
import com.utils.JsonUtils;
import com.utils.StrUtils;
import com.utils.lol.LOLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@BotCmd(funName = "LOL")
public class LoLSearchCommand extends BaseCommand {

    private Logger logger = LoggerFactory.getLogger(LoLSearchCommand.class);

    private String[] tierStr = {"Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ"};

    @Autowired
    private LolSettingDao settingDao;

    @Autowired
    private LolAreaDao areaDao;

    @Autowired
    private LolTierDao tierDao;


    public LoLSearchCommand() {
        super("召唤师搜索", "LOL玩家");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) {
        String userName = "";
        if (args.size() > 0) {
            userName = args.get(0).toLowerCase().trim();
            if (StrUtil.isBlank(userName)) {
                CmdUtil.sendMessage("请在指令后带玩家名称", userId, id, type);
                return;
            }
        }
        LolSetting setting = settingDao.findByName("cookie");
        if (ObjectUtil.isNotNull(setting)) {
            String value = setting.getValue();
            String result = LOLUtils.getInstanceByCookie(value).searchPlayer(userName);
            logger.info("得到LOL玩家信息：" + result);
            JSONObject obj = JsonUtils.getJsonObjectByJsonString(result);
            JSONArray players = obj.getJSONArray("players");

            String cookie = setting.getValue();
            StringBuilder sb = new StringBuilder();
            if (null != players) {
                if (players.size() == 0) {
                    CmdUtil.sendMessage("该玩家不存在，也可能是wegame炸了，你试试用wegame搜索看看？", userId, id, type);
                    return;
                }
                sb.append("玩家：").append(userName).append("\n");
                int max = 0;
                JSONObject maxObj = null;
                for (int i = 0; i < players.size(); i++) {
                    JSONObject player = players.getJSONObject(i);
                    int level = player.getIntValue("level");
                    if (level > max) {
                        max = level;
                        maxObj = player;
                    }
                }
                if (ObjectUtil.isNotNull(maxObj)) {
                    String openid = maxObj.getString("openid");
                    int area = maxObj.getIntValue("area");
                    int level = maxObj.getIntValue("level");
                    LolArea lolArea = areaDao.findById(area);
                    sb.append("大区：").append(lolArea.getAreaName()).append("\n");
                    sb.append("等级：").append(level).append("\n");

                    String json = LOLUtils.getInstanceByCookie(cookie).getUserInfo(openid, area);
                    JSONObject infoObj = JsonUtils.getJsonObjectByJsonString(json);
                    if (ObjectUtil.isNotNull(infoObj.getJSONObject("battle_count"))) {
                        JSONObject battle = infoObj.getJSONObject("battle_count");
                        sb.append("匹配对局(胜/负)：").append(battle.getIntValue("total_match_wins")).append("/").append(battle.getIntValue("total_match_losts")).append("\n");
                        sb.append("乱斗对局(胜/负)：").append(battle.getIntValue("total_arm_wins")).append("/").append(battle.getIntValue("total_arm_losts")).append("\n");
                        JSONArray seasonList = infoObj.getJSONArray("season_list");
                        if (CollectionUtil.isNotEmpty(seasonList)) {
                            JSONObject season = seasonList.getJSONObject(0);

                            LolTier tier = tierDao.findByTierId(season.getIntValue("tier"));
                            String tierShow;
                            if(ObjectUtil.isNull(tier)){
                                tierShow = "暂无段位";
                            } else {
                                if(tier.getTier() == 0 || tier.getTier() == 6 ||tier.getTier() == 7){
                                    tierShow = tier.getTierName();
                                } else {
                                    tierShow = tier.getTierName() + tierStr[season.getIntValue("queue")];
                                }
                            }

                            LolTier teamTier = tierDao.findByTierId(season.getIntValue("team_tier"));
                            String teamShow;
                            if(ObjectUtil.isNull(teamTier)){
                                teamShow = "暂无段位";
                            } else {
                                if(teamTier.getTier() == 0 || teamTier.getTier() == 6 ||teamTier.getTier() == 7){
                                    teamShow = tier.getTierName();
                                } else {
                                    teamShow = teamTier.getTierName() + tierStr[season.getIntValue("team_queue")];
                                }
                            }
                            sb.append("单双排位(胜/负)：").append(season.getIntValue("wins")).append("/").append(season.getIntValue("losses")).append("\n");
                            sb.append("单双段位：").append(tierShow).append("、胜点：").append(season.getIntValue("win_point")).append("点\n");
                            sb.append("灵活排位(胜/负)：").append(season.getIntValue("team_wins")).append("/").append(season.getIntValue("team_losses")).append("\n");
                            sb.append("灵活段位：").append(teamShow).append("、胜点：").append(season.getIntValue("team_win_point")).append("点\n");

                        }
                    } else {
                        sb.append("该玩家设置了权限！无法查看更多数据").append("\n");
                    }

                }
            }
            if (StrUtils.isNotEmpty(sb.toString())) {
                sb.append("\n").append("该功能默认查询玩家最高等级的区域\n若想查玩家在其他区域的信息，输入指令：#黑色玫瑰 Uzi");
                CmdUtil.sendMessage(sb.toString(), userId, id, type);
            }
        }
    }


}
